{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 3 DataFrame\n",
    "DataFrame 是一个表格型的数据结构，它含有一组有序的列，每列可以是不同类型的值。\n",
    "\n",
    "DataFrame 既有行索引也有列索引，它可以被看做是由Series组成的字典（共用同一个索引），数据是以二维结构存放的。\n",
    "\n",
    "- 类似多维数组/表格数据 (如excel, R中的data.frame)\n",
    "- 每列数据可以是不同的类型\n",
    "- 索引包括列索引和行索引"
   ],
   "id": "5063216ab3bbd2ea"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:07:39.190838Z",
     "start_time": "2025-01-17T04:07:39.187333Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# 通过ndarray构建DataFrame\n",
    "t = pd.DataFrame(np.arange(12).reshape((3,4))) #默认索引是0-2\n",
    "print(t)"
   ],
   "id": "8eb0cd853ce451e3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   0  1   2   3\n",
      "0  0  1   2   3\n",
      "1  4  5   6   7\n",
      "2  8  9  10  11\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:08:41.642100Z",
     "start_time": "2025-01-17T04:08:41.637850Z"
    }
   },
   "cell_type": "code",
   "source": [
    "array = np.random.randn(5,4)  # 5行4列的随机数组\n",
    "print(array)\n",
    "print('-'*50)\n",
    "df_obj = pd.DataFrame(array)\n",
    "print(df_obj.head()) #默认显示前5行"
   ],
   "id": "580eed13302d9659",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-0.34636926  0.71465616  1.24400831 -1.86620747]\n",
      " [ 1.92923362  0.30682638  0.13509932 -0.12810323]\n",
      " [ 0.42515953 -0.27984312  1.16889207  2.55444923]\n",
      " [-0.34046086  0.84136793  1.02520703 -0.01457746]\n",
      " [ 0.62916766 -0.42065887 -0.38600077 -0.33077459]]\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0 -0.346369  0.714656  1.244008 -1.866207\n",
      "1  1.929234  0.306826  0.135099 -0.128103\n",
      "2  0.425160 -0.279843  1.168892  2.554449\n",
      "3 -0.340461  0.841368  1.025207 -0.014577\n",
      "4  0.629168 -0.420659 -0.386001 -0.330775\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:09:39.049583Z",
     "start_time": "2025-01-17T04:09:39.046982Z"
    }
   },
   "cell_type": "code",
   "source": "print(t.loc[0]) #单独把某一行取出来,类型是series",
   "id": "62c29d053d58fee8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0\n",
      "1    1\n",
      "2    2\n",
      "3    3\n",
      "Name: 0, dtype: int64\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:09:55.601703Z",
     "start_time": "2025-01-17T04:09:55.595090Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 列表套字典变df\n",
    "d2 =[{\"name\" : \"xiaohong\" ,\"age\" :32,\"tel\" :10010},\n",
    "     { \"name\": \"xiaogang\" ,\"tel\": 10000} ,\n",
    "     {\"name\":\"xiaowang\" ,\"age\":22}]\n",
    "df6=pd.DataFrame(d2)\n",
    "print(df6) # 缺失值会用NaN填充\n",
    "print(type(df6.values)) # values是ndarray"
   ],
   "id": "c9ac8782ee6092ea",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       name   age      tel\n",
      "0  xiaohong  32.0  10010.0\n",
      "1  xiaogang   NaN  10000.0\n",
      "2  xiaowang  22.0      NaN\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:10:34.959110Z",
     "start_time": "2025-01-17T04:10:34.955571Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 初始化指定索引3-6的Series\n",
    "pd.Series(1, index=list(range(3,7)),dtype='float32')"
   ],
   "id": "4f467b6b77c963b3",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3    1.0\n",
       "4    1.0\n",
       "5    1.0\n",
       "6    1.0\n",
       "dtype: float32"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:11:37.883090Z",
     "start_time": "2025-01-17T04:11:37.878773Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#df中不同列可以是不同的数据类型,同一列必须是一个数据类型\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1, index=list(range(4)),dtype='float32'),\n",
    "             'D': np.array([1,2,3,4],dtype='int32'),\n",
    "             'E': [\"Python\",\"Java\",\"C++\",\"Ca\"],\n",
    "             'F': 'wangdao' }\n",
    "df_obj2 = pd.DataFrame(dict_data)\n",
    "print(df_obj2)"
   ],
   "id": "fe6170a715f55619",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4      Ca  wangdao\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:13:26.699950Z",
     "start_time": "2025-01-17T04:13:26.696044Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj2.index) #行索引,重点\n",
    "# df_obj2.index[0]=2  不可以单独修改某个索引值\n",
    "print(df_obj2.columns) #列索引，重点\n",
    "df_obj2.dtypes #每一列的数据类型，重点"
   ],
   "id": "102db07fcb72b97f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index([0, 1, 2, 3], dtype='int64')\n",
      "Index(['A', 'B', 'C', 'D', 'E', 'F'], dtype='object')\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "A            int64\n",
       "B    datetime64[s]\n",
       "C          float32\n",
       "D            int32\n",
       "E           object\n",
       "F           object\n",
       "dtype: object"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:06:23.806073Z",
     "start_time": "2025-01-17T04:06:23.801583Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 感受日期,初始化df，设置行索引，列索引\n",
    "dates = pd.date_range('20130101', periods=6) #默认freq='D'，即天\n",
    "df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))\n",
    "print(df)\n",
    "print('-'*50)\n",
    "print(df.index)"
   ],
   "id": "cbba6b9cb60b33e5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   A         B         C         D\n",
      "2013-01-01  0.094659  0.104898  0.761465 -0.713299\n",
      "2013-01-02  0.495772 -0.566425 -1.458355  1.362464\n",
      "2013-01-03 -0.403771 -1.069492 -0.720864  0.806441\n",
      "2013-01-04  0.245420 -0.118245  0.924616  0.713960\n",
      "2013-01-05  0.357956  1.076248  0.687772 -1.117846\n",
      "2013-01-06 -0.145108 -0.107885  0.844396  0.430415\n",
      "--------------------------------------------------\n",
      "DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',\n",
      "               '2013-01-05', '2013-01-06'],\n",
      "              dtype='datetime64[ns]', freq='D')\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:22:33.770674Z",
     "start_time": "2025-01-17T04:22:33.765678Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#取数据\n",
    "print(df_obj2)\n",
    "print('-'*50)\n",
    "print(type(df_obj2))\n",
    "print('-'*50)\n",
    "#pd中使用索引名来取某一行，或者列\n",
    "print(df_obj2['B'])\n",
    "print('-'*50)\n",
    "#把df的某一列取出来是series\n",
    "print(type(df_obj2['B']))"
   ],
   "id": "c9ea45b208b90f0a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4      Ca  wangdao\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "--------------------------------------------------\n",
      "0   2019-09-26\n",
      "1   2019-09-26\n",
      "2   2019-09-26\n",
      "3   2019-09-26\n",
      "Name: B, dtype: datetime64[s]\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.series.Series'>\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:22:34.479704Z",
     "start_time": "2025-01-17T04:22:34.475662Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#增加列数据，列名是自定义的\n",
    "df_obj2['G'] = df_obj2['D'] + 4\n",
    "print(df_obj2.head())"
   ],
   "id": "7cbd1da9a8119aca",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F  G\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao  5\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao  6\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao  7\n",
      "3  1 2019-09-26  1.0  4      Ca  wangdao  8\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T04:22:34.881492Z",
     "start_time": "2025-01-17T04:22:34.876844Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 删除列\n",
    "del(df_obj2['G'])\n",
    "print(df_obj2.head())"
   ],
   "id": "5c47aa7e5a94900c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4      Ca  wangdao\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "4242474c48bd7fa5"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
